import { IModalDetailProps } from '@/types/modal';
import { Modal } from 'antd';
import { useImperativeHandle, useState } from 'react';
import { orderDetail } from '@/api';
import { Order } from '@/types';

export default function OrderRoute(props: IModalDetailProps) {
  const [visible, setVisible] = useState(false);
  const [trackAni, setTrackAni] = useState(null);

  useImperativeHandle(props.mRef, () => {
    return {
      open
    };
  });

  const open = async (id: string) => {
    setVisible(true);
    const data = await orderDetail(id);
    setTimeout(() => {
      renderMap(data);
    }, 50);
  };

  const handleClose = () => {
    setVisible(false);
    trackAni?.cancel();
  };

  const renderMap = (orderDetail: Order.OrderItem) => {
    const cityName = orderDetail.cityName;
    const geo = new BMapGL.Geocoder();
    geo.getPoint(
      cityName,
      point => {
        if (point) {
          const bmap = new BMapGL.Map('allmap');
          bmap.centerAndZoom(point, 17);
          bmap.enableScrollWheelZoom();
          const routes = orderDetail.route;
          const targetRoutes = [];
          for (let i = 0; i < routes.length; i++) {
            targetRoutes.push(new BMapGL.Point(routes[i].lng, routes[i].lat));
          }
          const ployline = new BMapGL.Polyline(targetRoutes, {
            strokeColor: '#ed6c00',
            strokeWeight: 5,
            strokeOpacity: 1
          });
          setTimeout(start, 1000);
          // eslint-disable-next-line no-inner-declarations
          function start() {
            const trackAni = new BMapGLLib.TrackAnimation(bmap, ployline, {
              overallView: true,
              tilt: 30,
              duration: 20000,
              delay: 300
            });
            setTrackAni(trackAni);
            trackAni.start();
          }
        }
      },
      cityName
    );
  };

  return (
    <Modal
      title='路线轨迹'
      okText='确认'
      cancelText='取消'
      open={visible}
      onOk={handleClose}
      onCancel={handleClose}
      width={1100}
    >
      <div id='allmap' style={{ height: 500 }}></div>
    </Modal>
  );
}
